package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.dto.ChangePasswordRequest;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.User;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.PetService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.vo.PetInformationVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理模块")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PetService petService;

    // ==================== 模块一：用户中心模块新增接口 ====================

    @Operation(summary = "获取用户宠物列表")
    @GetMapping({"/my-pets", "/center/my-pets"})
    public Result<List<PetInformationVo>> getMyPets() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.getUserByUsername(username);
            
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            List<PetInformationVo> pets = petService.getUserPets(user.getId());
            return Result.success("获取成功", pets);
        } catch (Exception e) {
            log.error("获取用户宠物列表失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "修改用户密码")
    @PutMapping("/change-password")
    public Result<?> changePassword(@RequestBody ChangePasswordRequest request) {
        try {
            // 验证新密码和确认密码是否一致
            if (!request.getNewPassword().equals(request.getConfirmPassword())) {
                return Result.error("新密码和确认密码不一致");
            }
            
            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.getUserByUsername(username);
            
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            boolean success = userService.changePassword(user.getId(), request.getOldPassword(), request.getNewPassword());
            return success ? Result.success("密码修改成功") : Result.error("密码修改失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error("修改密码失败: " + e.getMessage());
        }
    }

    @Operation(summary = "上传用户头像")
    @PostMapping("/upload-avatar")
    public Result<?> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }
            
            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.getUserByUsername(username);
            
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 这里简化处理，实际应该上传到文件服务器或OSS
            // 临时方案：保存文件名作为头像URL
            String fileName = file.getOriginalFilename();
            String avatarUrl = "/uploads/avatars/" + System.currentTimeMillis() + "_" + fileName;
            
            String result = userService.uploadAvatar(user.getId(), avatarUrl);
            if (result != null) {
                Map<String, String> data = new HashMap<>();
                data.put("avatarUrl", result);
                return Result.success("上传成功", data);
            }
            return Result.error("上传失败");
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return Result.error("上传失败: " + e.getMessage());
        }
    }

    // ==================== 原有接口 ====================

    @Operation(summary = "用户注册新账号")
    @PostMapping("/register")
    public Result<?> register(@RequestBody RegisterRequest request) {
        try {
            User user = new User();
            user.setUsername(request.getUsername());
            user.setPassword(request.getPassword());
            user.setEmail(request.getEmail());
            user.setPhone(request.getPhone());
            user.setRealName(request.getRealName());

            boolean success = userService.register(user);
            return success ? Result.success("注册成功") : Result.error("注册失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("注册失败", e);
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取当前登录用户的详细信息")
    @GetMapping("/info")
    public Result<User> getUserInfo() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.getUserByUsername(username);
            if (user != null) {
                // 清除密码信息
                user.setPassword(null);
                return Result.success(user);
            }
            return Result.error("用户不存在");
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败");
        }
    }

    @Operation(summary = "管理员分页查询所有注册用户")
    @GetMapping("/admin/users")
    public PageResult<User> getUserList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            IPage<User> page = userService.getUserList(pageNum, pageSize);
            return PageResult.success(page);
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "用户修改个人资料")
    @PutMapping("/update")
    public Result<?> updateUser(@RequestBody User user) {
        try {
            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);

            if (currentUser == null) {
                return Result.error("用户不存在");
            }

            // 只能修改自己的信息
            user.setId(currentUser.getId());
            boolean success = userService.updateUser(user);
            return success ? Result.success("更新成功") : Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @Operation(summary = "管理员删除指定用户账号")
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        try {
            boolean success = userService.deleteUser(id);
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查询用户拥有的角色与权限信息")
    @GetMapping("/roles")
    public Result<?> getUserRoles() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.getUserByUsername(username);
            
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 构建角色信息
            String role = user.getUserType() == 2 ? "ROLE_ADMIN" : "ROLE_USER";
            Map<String, Object> roleInfo = new HashMap<>();
            roleInfo.put("role", role);
            roleInfo.put("userType", user.getUserType());
            return Result.success("角色信息", roleInfo);
        } catch (Exception e) {
            log.error("查询角色信息失败", e);
            return Result.error("查询失败");
        }
    }

    @Data
    public static class RegisterRequest {
        private String username;
        private String password;
        private String email;
        private String phone;
        private String realName;
    }
}
